<template>
  <div class="c-stock" :style="{height}">
    <el-button v-if="route.query.type !== '1'" class="gz" link type="primary" @click.stop="rcHandle">关注</el-button>
    <c-echarts-stock ref="echartsRef"></c-echarts-stock>
  </div>
</template>

<script setup>
import {inject, onMounted, ref, defineProps, toRefs, watch, onBeforeUnmount, reactive, computed} from 'vue';
import {getFuturesDetail, getRequestData, getStockDetail} from '../utils/getData.js';
import CEchartsStock from "./c-echarts-stock.vue";
import {
  getFuturesParams,
  notify,
  timeRefresh
} from "../utils/commonScript.js";
import {useRoute} from "vue-router";
import {POST} from "../api/index.js";
import CLCandlestick from "../utils/CLCandlestick.js";
import EchartsOption from "../utils/EchartsOption.js";

const props = defineProps({
  options: {
    type: Object,
    default: {}
  },
  height: {
    type: String,
    default: '500px'
  },
})

const {options} = toRefs(props)
const timer = ref(null)

const rcHandle = () => {
  POST('/market/user', {
    stockCode: options.value.stockCode
  }).then(res => {
    notify('关注成功')
  })

}

watch(options, (val) => {
  clearInterval(timer.value)
  getData(true)
  if(val.isAuto) {
    autoHandle()
  }
}, {
  deep: true
})

const echartsRef = ref(null)

const route = useRoute()

const setOption = (data, isNewDom) => {
  const echartsData = new CLCandlestick(data.klines, options.value).getData()
  options.value.isShowX = true
  const option = new EchartsOption(echartsData, options.value).getOption()

  echartsRef.value.setEchartsOption(option, isNewDom)
}

// 获取股票数据并渲染
const getStockData = (code, type, isNewDom) => {
  getRequestData({code, type}, (data) => {
    setOption(data, isNewDom)
  })
}

const getData = (isNewDom) => {
  // 获取数据
  if(route.query.type === '1') {
    getFuturesDetail(getFuturesParams(options.value.stockCode, options.value.stockType), (data) => {
      setOption({name: options.value.stockName, klines: data}, isNewDom)
    })
  } else {
    getStockData(options.value.stockCode, options.value.stockType, isNewDom)
  }
}

const autoHandle = () => {
  timeRefresh(() => {
    timer.value = setInterval(() => {
      getData()
    }, 30000)
  })
}

onMounted(() => {
  // 基于准备好的dom，初始化echarts实例
  getData()
  if(options.value.isAuto) {
    autoHandle()
  }
})

onBeforeUnmount(()=> {
  clearInterval(timer.value)
  timer.value = null
})

</script>

<style scoped>
.c-stock{
  display: flex;
  position: relative;
  .gz{
    position: absolute;
    top: 15px;
    right: 40px;
    z-index: 333;
  }
}
</style>
